package ro.myApp.client.helpers;

import java.io.Serializable;
import java.security.acl.Group;

import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Logger;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.faces.Redirect;
import org.jboss.seam.log.Log;
import org.jboss.seam.security.Credentials;
import org.jboss.seam.security.Identity;

@Name("authenticator")
public class Authenticator implements Serializable{
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 6803231892738753154L;

	@Logger
	private Log log;
	
	@In
	private Credentials credentials;
	
	@In
	private Identity identity;
	
	@In
	private Redirect redirect;
	
	public boolean authenticate()  {
		
		String name = credentials.getUsername();
		String pwd = credentials.getPassword();

		log.info("autenthicate: '{0}': '{1}'", name, pwd);
		log.info("principal: '{0}': ", identity.getPrincipal());
		log.info("subject: '{0}': ", identity.getSubject());
		log.info("on subject '{0}'",  identity.getSubject().getPrincipals(Group.class));
		log.info("is logged in: '{0}'", identity.isLoggedIn());
	
		//login user and set rights
		if (null!=name)
			for (Group g : identity.getSubject().getPrincipals(Group.class))
				identity.addRole(g.getName());
		
		
		//if the user has clicked the login link define a default page to go to in case of successful login
		if (null==redirect.getViewId()){
			org.jboss.seam.faces.Redirect.instance().setViewId("/index.jspx");
			org.jboss.seam.faces.Redirect.instance().clearDirty();
		}
		return true;
	}
	
}